package com.qf.forumproject.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.qf.forumproject.entity.QfUser;
import com.qf.forumproject.loginAndRegister.service.QfUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    HashedCredentialsMatcher hashedCredentialsMatcher;

    @Autowired
    EhCacheManager ehCacheManager;

    @Autowired
    QfUserService qfUserService;


    // 当IOC容器完成DI后，会调用如下注解的方法
    @PostConstruct
    public void initCostmomReal(){
        //设置加密对象
        this.setCredentialsMatcher(hashedCredentialsMatcher);

        // 设计缓存管理对象
        this.setCacheManager(ehCacheManager);
        this.setCachingEnabled(true); // 开启缓存功能
        this.setAuthenticationCachingEnabled(true); // 设置身份认证使用缓存
        this.setAuthorizationCachingEnabled(true);// 设置授权信息使用缓存


    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        final String username = (String) authenticationToken.getPrincipal();

        QfUser user = (QfUser) getUserFromDB(username);

        // 注意：这里需要返回该token对应的AuthenticationInfo对象，并不需要对密码进行比对
        // 比对密码的过程由shiro后续自动完成
        // 这里只需要把数据库中的用户名和密码封装到 AuthenticationInfo 对象中即可。
        // 第三个参数，是 盐的字节数组
        final SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),this.getName());

        return simpleAuthenticationInfo;
    }

    // 根据用户名查询用户信息
    private  QfUser getUserFromDB(String username) {

        // 尝试从自定的缓存中，先查询一下是否由匹配的数据

        final QueryWrapper<QfUser> userQueryWrapper = new QueryWrapper<>();

        userQueryWrapper.eq("username",username);

        final QfUser qfUser = qfUserService.getOne(userQueryWrapper);

        return qfUser;

    }
}
